import { Input, Modal, Pagination, Table, Tree } from "antd";
import { useCallback, useEffect, useState } from "react";
import { request } from "../../../Api/api";
import { getUserTypeName } from "../../../Api/name";

const SelectExaminees = ({
  open = false,
  onOk = () => {},
  onCancel = () => {},
}) => {
  const [examineess, setExamineess] = useState({
    departmentIds: [],
    jobIds: [],
  });
  const [examineeIds, setExamineeIds] = useState([]);
  const [departmentTrees, setDepartmentTrees] = useState([]);
  const [departmentExpandedKeys, setDepartmentExpandedKeys] = useState([]);
  const [jobs, setJobs] = useState([]);
  const [examinees, setExaminees] = useState([]);
  const [jobPage, setJobPage] = useState({
    page: 1,
    limit: 5,
  });
  const [jobTotal, setJobTotal] = useState(0);
  const [jobWhere, setJobWhere] = useState({ key: "" });
  const [examineePage, setExamineePage] = useState({
    page: 1,
    limit: 5,
  });
  const [examineeTotal, setExamineeTotal] = useState(0);
  const [examineeWhere, setExamineeWhere] = useState({ key: "" });
  const getAllKeys = useCallback((data) => {
    let keys = [];
    data.forEach((item) => {
      keys.push(item.id);
      if (item.childrenDeps) {
        keys = keys.concat(getAllKeys(item.childrenDeps));
      }
    });
    return keys;
  }, []);
  const bind = useCallback(async () => {
    const res1 = await request("/department/tree", {}, "GET");
    if (res1.code >= 0) {
      setDepartmentTrees(res1.data);
      setDepartmentExpandedKeys(getAllKeys(res1.data));
    }
    const res2 = await request(
      "/exam/filterJobs",
      {
        departmentIds: examineess.departmentIds.join(","),
        ...jobPage,
        ...jobWhere,
      },
      "GET"
    );
    if (res2.code >= 0) {
      setJobs(res2.data.data);
      setJobTotal(res2.data.total);
    }
    const res3 = await request(
      "/exam/filterExaminees",
      {
        departmentIds: examineess.departmentIds.join(","),
        jobIds: examineess.jobIds.join(","),
        ...examineePage,
        ...examineeWhere,
      },
      "GET"
    );
    if (res3.code >= 0) {
      setExaminees(res3.data.data);
      setExamineeTotal(res3.data.total);
    }
  }, [jobPage, jobWhere, examineePage, examineeWhere, examineess, getAllKeys]);
  useEffect(() => {
    async function fetchData() {
      await bind();
    }
    fetchData();
  }, [bind]);
  const jobColumns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      width: 100,
      ellipsis: true,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text) => new Date(text).toLocaleString(),
      width: 150,
      ellipsis: true,
    },
    {
      title: "描述",
      dataIndex: "explain",
      key: "explain",
      width: 200,
      ellipsis: true,
    },
    {
      title: "部门",
      dataIndex: "department",
      key: "department",
      width: 100,
      ellipsis: true,
    },
  ];
  // public string name { get; set; }
  // public string account { get; set; }
  // public string phone { get; set; }
  // public string jobName { get; set; }
  // public string depName { get; set; }
  // public int type { get; set; }
  const examineeColumns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      width: 100,
      ellipsis: true,
    },
    {
      title: "账号",
      dataIndex: "account",
      key: "account",
      width: 100,
      ellipsis: true,
    },
    {
      title: "手机号",
      dataIndex: "phone",
      key: "phone",
      width: 100,
      ellipsis: true,
    },
    {
      title: "职位",
      dataIndex: "jobName", // jobName
      key: "jobName",
      width: 100,
      ellipsis: true,
    },
    {
      title: "部门",
      dataIndex: "depName", // depName
      key: "depName",
      width: 100,
      ellipsis: true,
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (text) => {
        return getUserTypeName(text);
      },
      width: 100,
      ellipsis: true,
    },
  ];
  return (
    <Modal
      centered
      width={"80%"}
      open={open}
      onOk={() => onOk({ ...examineess, examineeIds })}
      onCancel={() => {
        setExamineeIds([]);
        setExamineess({ departmentIds: [], jobIds: [] });
        setJobPage({ page: 1, limit: 5 });
        setJobWhere({ key: "" });
        setExamineePage({ page: 1, limit: 5 });
        setExamineeWhere({ key: "" });
        onCancel();
      }}
      title="选择考生"
      okText="确定"
      cancelText="取消"
    >
      <div
        style={{
          height: "calc(70vh)",
          overflow: "auto",
          padding: "10px",
        }}
      >
        <div
          style={{
            display: "flex",
          }}
        >
          <div style={{ flex: 1 }}>
            <Tree
              blockNode
              checkStrictly
              expandedKeys={departmentExpandedKeys}
              onExpand={(expandedKeys) => {
                setDepartmentExpandedKeys(expandedKeys);
              }}
              treeData={departmentTrees}
              checkable
              selectedKeys={examineess.departmentIds}
              onCheck={(checkedKeys) => {
                console.log("onCheck", checkedKeys.checked);
                setExamineess({
                  ...examineess,
                  departmentIds: checkedKeys.checked,
                });
              }}
              fieldNames={{
                title: "name",
                key: "id",
                children: "childrenDeps",
              }}
            />
          </div>
          <div style={{ flex: 2 }}>
            <Input
              style={{ display: "block" }}
              placeholder="搜索"
              onChange={(e) => setJobWhere({ key: e.target.value })}
            />
            <Table
              rowKey={({ id }) => id}
              dataSource={jobs}
              pagination={false}
              columns={jobColumns}
              rowSelection={{
                selectedRowKeys: examineess.jobIds,
                onChange: (selectedRowKeys, selectedRows) => {
                  setExamineess({
                    ...examineess,
                    jobIds: selectedRowKeys,
                  });
                },
              }}
            />
            <Pagination
              current={jobPage.page}
              pageSize={jobPage.limit}
              total={jobTotal}
              showSizeChanger
              onChange={(page, limit) => setJobPage({ page, limit })}
            ></Pagination>
          </div>
        </div>
        <div>
          <Input
            style={{ display: "block" }}
            placeholder="搜索"
            onChange={(e) => setExamineeWhere({ key: e.target.value })}
          />
          <Table
            rowKey={({ id }) => id}
            dataSource={examinees}
            pagination={false}
            columns={examineeColumns}
            rowSelection={{
              selectedRowKeys: examineeIds,
              onChange: (selectedRowKeys, selectedRows) => {
                setExamineeIds(selectedRowKeys);
              },
            }}
          />
          <Pagination
            current={examineePage.page}
            total={examineeTotal}
            pageSize={examineePage.limit}
            showSizeChanger
            onChange={(page, limit) => setExamineePage({ page, limit })}
          ></Pagination>
        </div>
      </div>
    </Modal>
  );
};

export default SelectExaminees;
